<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Validation\ValidationException;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {

        // 第三方接口返回异常
        if ($exception instanceof ApiResponseException) {
            return response()->json([
                'message' => '加载失败，请稍后再试',
                'code' => 500002,
//                'data'    => $exception->getMessage()
            ], 500);
        }

        // 表单验证异常
        if ($exception instanceof ValidationException) {
            $message = $exception->validator->errors()->first();
            return response()->json([
                'message' => $message,
                'code' => 422001,
                'data'    => []
            ]);
        }

        // 普通异常返回
        if ($exception instanceof ApiException) {

            return response()->json($exception->getResponseData());
        }

        //模型未找到异常
        if ($exception instanceof ModelNotFoundException) {
            \Log::debug("404", ["message" => $exception->getMessage()]);
            return response()->json([
                'message' => '加载失败，请稍后再试!',
                'code' => 404001
            ]);
        }
        //支付异常
        if ($exception instanceof \Yansongda\Pay\Exceptions\Exception) {
            \Log::debug("404", ["message" => $exception->getMessage()]);
            return response()->json([
                'message' => $exception->getMessage(),
                'code' => 404001
            ]);
        }

        /* 后台表单保存异常信息抛出 */
        if ($exception instanceof FormException) {
            return response()->json($exception->getResponseData());
        }

        return parent::render($request, $exception);
    }
}
